package com.ssm.property.server.controller.building;

import com.github.pagehelper.PageInfo;
import com.jee.ssm.common.support.Const;
import com.jee.ssm.common.utils.UUIDFactory;
import com.jee.ssm.common.web.json.Tip;
import com.jee.ssm.common.web.param.ParamMap;
import com.ssm.property.dao.model.building.Building;
import com.ssm.property.dao.model.residence.Residence;
import com.ssm.property.dao.model.room.Room;
import com.ssm.property.rpc.api.building.BuildingService;
import com.ssm.property.rpc.api.estate.EstateService;
import com.ssm.property.rpc.api.residence.ResidenceService;
import com.ssm.property.rpc.api.room.RoomService;
import com.ssm.property.rpc.api.unit.UnitService;
import com.ssm.upms.dao.model.Account;
import com.ssm.upms.log.AdminControllerLog;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

/**
* 楼栋管理 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/building")
public class BuildingController {


    /**
     * 进入楼栋添加页面 携带一个生成的id --> longId
     * @param model 返回的实体容器
     * @return 添加页面
     */
    @RequestMapping(value="/add")
    @RequiresPermissions("building:add")
    public String add(HttpServletRequest request, ModelMap model){
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        model.put("type",account.getType());
        if(account.getType()==21) {
            model.put("residence", residenceService.selectById(account.getInfoId().split(",")[1]));
        }
        model.put("longId", UUIDFactory.getStringId());
        return "manager/building/add";
    }

    /**
     * 批量添加楼栋
     * @return 添加页面
     */
    @RequestMapping(value = "/adds")
    @RequiresPermissions("building:add")
    public String adds(HttpServletRequest request, ModelMap model ){
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        model.put("type",account.getType());
        if(account.getType()==21) {
            model.put("residence", residenceService.selectById(account.getInfoId().split(",")[1]));
        }
        return  "manager/building/adds";
    }


    /**
     * 进入楼栋编辑页面
     * @param model 返回楼栋的容器
     * @param id 楼栋id
     * @return 编辑页面
     */
    @RequestMapping(value="/edit")
    @RequiresPermissions("building:edit")
    public String edit(HttpServletRequest request, ModelMap model, @RequestParam String id) {
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        model.put("type",account.getType());
        Building building = buildingService.selectById(id);
        building.setResidence(residenceService.selectById(building.getResidenceId()));
        model.put("data",building);
        return "manager/building/edit";
    }


    /**
     * 楼栋添加
     * @param building 带id的楼栋对象
     * @return 成功状态
     */
    @RequestMapping(value="/save")
    @ResponseBody
    @RequiresPermissions("building:add")
    @AdminControllerLog(description = "添加楼栋" )
    public Tip save(Building building,HttpServletRequest request)  {
        try {
           System.out.println(building.getNumber());
            ParamMap paramMap=new ParamMap(request);
            paramMap.put("residenceId",building.getResidenceId());
            paramMap.put("number",building.getNumber());
            if(buildingService.count(paramMap)>0){
                return  new Tip(1,"楼栋编号已存在");
            }
            buildingService.insert(building);
            return new Tip();
        } catch (Exception e) {
           // e.printStackTrace();
            return new Tip(1,"添加失败！");
        }

    }



    /**
     * 批量添加楼栋
     * @param building 带id的楼栋对象
     * @return 成功状态
     */
    @RequestMapping(value="/saves")
    @ResponseBody
    @RequiresPermissions("building:add")
    @AdminControllerLog(description = "添加楼栋" )
    public Tip saves(Building building,String count,HttpServletRequest request)  {
        try {
            int number=Integer.parseInt(building.getNumber());
            int total=Integer.parseInt(count)+number;
            ParamMap paramMap=new ParamMap(request);
            for(int i=number;i<total;i++){
                paramMap.put("residenceId",building.getResidenceId());
                paramMap.put("number",String.valueOf(i));
                if(buildingService.count(paramMap)>0){i=i+1;}
                building.setId(UUIDFactory.getStringId());
                building.setNumber(String.valueOf(i));
                building.setBuildTime(building.getBuildTime());
                building.setResidenceId(building.getResidenceId());
                buildingService.insert(building);
            }
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"批量添加失败");
        }
    }

    /**
     * 根据 id 修改楼栋
     * @param building 带id的楼栋对象
     * @return 成功状态
     */
    @RequestMapping(value="/update")
    @ResponseBody
    @RequiresPermissions("building:edit")
    @AdminControllerLog(description = "修改楼栋" )
    public Tip update(Building building,HttpServletRequest request) {
        try {
            if (!buildingService.selectById(request.getParameter("id")).getNumber().equals(building.getNumber())){
                ParamMap paramMap=new ParamMap(request);
                paramMap.put("residenceId",building.getResidenceId());
                paramMap.put("number",building.getNumber());
                if(buildingService.count(paramMap)>0){
                    return  new Tip(1,"楼栋编号已存在");
                }
            }
            buildingService.updateById(building);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"修改失败！");
        }

    }


    /**
     * 根据 id 删除楼栋
     * @param id 楼栋id
     * @return 成功状态
     */
    @RequestMapping(value="/delete")
    @ResponseBody
    @RequiresPermissions("building:delete")
    @AdminControllerLog(description = "删除楼栋" )
    public Tip delete(@RequestParam String id) {

        try {
            // 查询楼栋下的房屋id
            List<Room> roomList = roomService.selectByBuildingId(id);
            if(roomList!=null && !roomList.isEmpty()){
                for (Room room:roomList) {
                    roomService.deleteById(room.getId());//删除房间
                }
            }
        /*    //楼栋下面的设备
            List<Equipment> equipmentList = equipmentService.selectByBuildingId(id);
            if(equipmentList!=null && !equipmentList.isEmpty()){
                for (Equipment equipment:equipmentList) {
                    List<Card> cardList = cardService.selectByEquipmentId(equipment.getId());
                    if(cardList!=null && !cardList.isEmpty()){
                        for (Card card:cardList) {
                            cardService.deleteById(card.getId());//删卡
                        }
                    }

                }
            }
            if(equipmentList!=null && !equipmentList.isEmpty()){
                for (Equipment equipment:equipmentList) {
                    equipmentCardService.deleteByEquipmentId(equipment.getId());//根据设备id 删除设备与卡关联信息
                    equipmentService.selectById(equipment.getId());//删设备
                }
            }
            userRoomService.deleteByBuildingId(id);*/
            unitService.deleteByBuildingId(id);//删单元
            buildingService.deleteById(id);//删楼栋
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"删除失败！");
        }

    }

    /**
     * 根据 id 列表批量删除
     * @param ids 楼栋id List
     * @return 成功状态
     */
    @RequestMapping(value="/deleteByIds")
    @ResponseBody
    @RequiresPermissions("building:delete")
    @AdminControllerLog(description = "批量删除楼栋" )
    public Tip deleteByIds(@RequestParam("ids") List<String> ids) {

        try {
            buildingService.deleteByIds(ids);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"批量删除失败！");
        }
    }


    /**
     * 根据 id 查找楼栋
     * @param id 楼栋id
     * @return 楼栋对象 json
     */
    @RequestMapping(value="/findJson")
    @ResponseBody
    @RequiresPermissions("building:list")
    public Building find(@RequestParam String id) {

        return buildingService.selectById(id);
    }


    /**
     * 获取楼栋列表 获取全部 不分页
     * @param request 请求参数
     * @return 楼栋列表页面
     */
    @RequestMapping(value="/all")
    @RequiresPermissions("building:list")
    public String all(HttpServletRequest request, ModelMap modelMap) {

        return list(request,modelMap,1,0);
    }


    /**
     * 获取楼栋列表 分页
     * @param request 请求参数
     * @param page 第几页
     * @param size 每页大小
     * @return 楼栋列表页面
     */
    @RequestMapping(value="/list")
    @RequiresPermissions("building:list")
    public String list(HttpServletRequest request, ModelMap modelMap, Integer page, Integer size) {
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute(Const.ACCOUNT);
        ParamMap paramMap = new ParamMap(request);
        if (account.getType() == 2) {
            paramMap.put("estateId", account.getInfoId());
        }else if(account.getType() == 21){
            if(estateService.selectById(account.getInfoId().split(",")[0]) != null){
                paramMap.put("estateId",account.getInfoId().split(",")[0]);
            }
            String residenceId = account.getInfoId().split(",")[1];
            paramMap.put("residenceId",residenceId);
            //楼栋数量
            Long countBuild = buildingService.countBuild(paramMap);
            modelMap.put("countBuild",countBuild);
            //单元数量
            Long countUnit = buildingService.countUnit(paramMap);
            modelMap.put("countUnit",countUnit);
            //房间数量
            Long countRoom = buildingService.countRoom(paramMap);
            modelMap.put("countRoom",countRoom);
            //男性数量
            Long countMale = buildingService.countMale(paramMap);
            modelMap.put("countMale",countMale);
            //女性数量
            Long countFemale = buildingService.countFemale(paramMap);
            modelMap.put("countFemale",countFemale);
            //60以上
            Long countOld = buildingService.countOld(paramMap);
            modelMap.put("countOld",countOld);
            //16以下
            Long countChild = buildingService.countChild(paramMap);
            modelMap.put("countChild",countChild);
        }/*else if(account.getType()==5){
            List<PoliceResidence> policeResidenceList= policeResidenceService.findByPoliceId(account.getInfoId());
            List<String> policeIdList=new ArrayList<String>();
            if(policeResidenceList.size()>0){
                for(PoliceResidence pr:policeResidenceList){
                    policeIdList.add(pr.getResidenceId());
                }
            }else{
                policeIdList.add("0");
            }

            paramMap.put("policeIdList", policeIdList);
        }*/
        List<Residence> residences = residenceService.listWithoutPage(paramMap);//搜索下拉框选择小区
        PageInfo<Building> pageInfo=buildingService.list(paramMap,page,size);

        for(Building building:pageInfo.getList()){
            building.setResidence(residenceService.selectById(building.getResidenceId()));
        }
        modelMap.put("residences",residences);//搜索下拉框选择小区
        modelMap.put("type",account.getType());
        modelMap.put("pageInfo",pageInfo);
        modelMap.putAll(paramMap);
        return "manager/building/list";
    }

    /**
     * 获取楼栋列表
     * @return 单元列表页面
     */
    @RequestMapping(value="/checklist")
    @RequiresPermissions("building:list")
    public String checklist(@RequestParam String residenceId, ModelMap modelMap) {
        List<Building> list=buildingService.chooseList(residenceId);
        for(Building building:list){
            building.setResidence(residenceService.selectById(building.getResidenceId()));
        }
        modelMap.put("list",list);
        return "manager/building/chooseBuilding";
    }

    /**
     * 网格员授权楼栋
     * @param gridId
     * @return
     */
    @RequestMapping(value = "/findByGridInfo")
    public String findByGridInfo(String gridId,ModelMap modelMap, ParamMap paramMap){
      List<Residence> residenceList=residenceService.listAll(null);
      paramMap.put("gridId",gridId);
      for(Residence residence:residenceList){
          paramMap.put("residenceId",residence.getId());
          residence.setBuildings(buildingService.listAll(paramMap));
      }
      modelMap.put("residenceList",residenceList);
        return  "manager/grid/grid-list";
    }



    /**
     * 小区楼栋数量
     * @return
     */
    @RequestMapping(value = "/countName")
    @ResponseBody
    public Map<String, Object> countName(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Building building = new Building();
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute(Const.ACCOUNT);
        if (account.getType() == 2) {
            building.setIntro(account.getInfoId());
        }else if(account.getType() == 21){
            building.setResidenceId(account.getInfoId().split(",")[1]);
        }else if(account.getType() == 5){
            building.setNumber(account.getInfoId());
        }

        List<Building> queryCommunityForList = buildingService.countName(building);
        /*int length = queryCommunityForList.size();
        String[] nameArray = new String[length];
        List<Echat> list = new ArrayList<Echat>();
        for(int i = 0 ;i<nameArray.length; i++  ){
            nameArray [i] = queryCommunityForList.get(i).getResidenceId();  //获取省份
        }
        for(Building community : queryCommunityForList){
            building.setResidenceId(community.getId());
            Building bd = buildingService.countNumber(building);
            Echat echat= new Echat();
            echat.setValue(bd.getResidenceId());
            echat.setName(community.getResidenceId());
            list.add(echat);
        }
        map.put("value",list);
        map.put("name",nameArray);*/
        return map;
    }




    /**
     * 小区建成时间统计
     * @return
     */
    @RequestMapping(value = "/countName2")
    @ResponseBody
    public Map<String, Object> countName2(HttpServletRequest request) throws Exception {
        Building building = new Building();
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute(Const.ACCOUNT);
        if (account.getType() == 2) {
            building.setIntro(account.getInfoId());
        }else if(account.getType() == 21){
            building.setResidenceId(account.getInfoId().split(",")[1]);
        }else if(account.getType() == 5){
            building.setNumber(account.getInfoId());
        }

        Map<String, Object> map = new HashMap<String, Object>();

        List<Building> queryCommunityForList = buildingService.countName2(building);
    /*    int length = queryCommunityForList.size();
        String[] nameArray = new String[length];
        List<Echat> list = new ArrayList<Echat>();
        for(int i = 0 ;i<nameArray.length; i++  ){
            nameArray [i] = queryCommunityForList.get(i).getAuxiliary();  //获取省份
        }
        for(Building community : queryCommunityForList){
            building.setAuxiliary(community.getAuxiliary());
            Building bd = buildingService.countNumber2(building);
            Echat echat= new Echat();
            echat.setValue(bd.getAuxiliary());
       *//*     echat.setName(community.getAuxiliary());*//*
            list.add(echat);
                map.put("value",list);
        map.put("name",nameArray);
        }*/

        return map;
    }


    /**
     * 楼栋数据导出
     * @param request
     * @param response
     * @param session
     * @throws IOException
     */
    @RequestMapping(value = "/exportEcxel")
    @RequiresPermissions("building:exportEcxel")
    public void exportEcxel(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        ParamMap paramMap = new ParamMap(request);
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        if(account.getType() == 2) {
            paramMap.put("estateId", account.getInfoId());
        }else if (account.getType() == 21){
            paramMap.put("residenceId",account.getInfoId().split(",")[1]);
        }else if(account.getType() == 5){
            paramMap.put("policeId", account.getInfoId());
        }
        List<Building> list = buildingService.listWithoutPage(paramMap);
        String originFileUrl = request.getServletContext().getRealPath("/download/info.xlsx");
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Building.class, list);
        FileOutputStream fos = new FileOutputStream(originFileUrl);
        workbook.write(fos);

        String fileName = "楼栋导出.xls";
        fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        //设置文件MIME类型
        response.setContentType(request.getServletContext().getMimeType(fileName));
        //设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //读取文件
        InputStream in = new FileInputStream(originFileUrl);
        OutputStream out = response.getOutputStream();

        //写文件
        int b;
        while((b=in.read()) != -1) {
            out.write(b);
        }
        fos.close();
        in.close();
        out.close();
    }


    /**
     * 获取楼栋下的住户
     * @param request 请求参数
     * @return 住户列表
     */
 /*   @RequestMapping(value="/user")
    public String user(HttpServletRequest request, ModelMap modelMap) {

        ParamMap paramMap=new ParamMap(request);
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        List<User> users = userService.selectByBuildingId(paramMap);
        modelMap.put("type",account.getType());
        modelMap.put("users",users);
        modelMap.putAll(paramMap);
        return "manager/building/user";
    }*/

    /**
     * 进入小区详情页面
     * @param modelMap 返回的实体容器
     * @return
     */
    @RequestMapping(value="/buildDetail")
    public String buildDetail(HttpServletRequest request, ModelMap modelMap, String residenceId, String id, Integer page, Integer size){
        ParamMap paramMap=new ParamMap(request);
        paramMap.put("id",id);
        //楼栋数量
        Long countBuild = buildingService.countBuild(paramMap);
        modelMap.put("countBuild",countBuild);
        //单元数量
        Long countUnit = buildingService.countUnit(paramMap);
        modelMap.put("countUnit",countUnit);
        //房间数量
        Long countRoom = buildingService.countRoom(paramMap);
        modelMap.put("countRoom",countRoom);
        //男性数量
        Long countMale = buildingService.countMale(paramMap);
        modelMap.put("countMale",countMale);
        //女性数量
        Long countFemale = buildingService.countFemale(paramMap);
        modelMap.put("countFemale",countFemale);
        //60以上
        Long countOld = buildingService.countOld(paramMap);
        modelMap.put("countOld",countOld);
        //16以下
        Long countChild = buildingService.countChild(paramMap);
        modelMap.put("countChild",countChild);

        //特殊人群总人数 sensitiveCount 1：涉恐人员，2：涉稳人员，3：重大刑事犯罪前科人员，4：涉毒人员，5：肇事肇祸精神病人6：重点上访人员
        Long sensitiveCount = buildingService.sensitiveCount(paramMap);
        modelMap.put("sensitiveCount",sensitiveCount);

       /* //涉恐人员人数 terrorismCount
        Long terrorismCount = buildingService.terrorismCount(paramMap);
        modelMap.put("terrorismCount",terrorismCount);
        paramMap.put("sensitiveStatus","1");
        List<Card> terrorism=cardService.selectBySensitive(paramMap);
        modelMap.put("terrorism",terrorism);

        //涉稳人员人数 stabilityCount
        Long stabilityCount = buildingService.stabilityCount(paramMap);
        modelMap.put("stabilityCount",stabilityCount);
        paramMap.put("sensitiveStatus","2");
        List<Card> stability=cardService.selectBySensitive(paramMap);
        modelMap.put("stability",stability);

        //重大刑事犯罪前科人员人数 criminalCount
        Long criminalCount = buildingService.criminalCount(paramMap);
        modelMap.put("criminalCount",criminalCount);
        paramMap.put("sensitiveStatus","3");
        List<Card> criminal=cardService.selectBySensitive(paramMap);
        modelMap.put("criminal",criminal);

        //涉毒人数 drugsCount
        Long drugsCount = buildingService.drugsCount(paramMap);
        modelMap.put("drugsCount",drugsCount);
        paramMap.put("sensitiveStatus","4");
        List<Card> drugs=cardService.selectBySensitive(paramMap);
        modelMap.put("drugs",drugs);

        //肇事肇祸精神病人人数 psychosisCount
        Long psychosisCount = buildingService.psychosisCount(paramMap);
        modelMap.put("psychosisCount",psychosisCount);
        paramMap.put("sensitiveStatus","5");
        List<Card> sensitive=cardService.selectBySensitive(paramMap);
        modelMap.put("sensitive",sensitive);

        //重点上访人员人数 petitionCount
        Long petitionCount = buildingService.petitionCount(paramMap);
        modelMap.put("petitionCount",petitionCount);
        paramMap.put("sensitiveStatus","6");
        List<Card> petition=cardService.selectBySensitive(paramMap);
        modelMap.put("petition",petition);

        //门禁卡
        Date currentDate=new Date();
        paramMap.put("currentDate",currentDate);

        modelMap.put("id", id);
        PageInfo<Card> pageDetail=cardService.listOfResidence(paramMap,page,size);
        modelMap.put("pageDetail",pageDetail);*/
        /*PageInfo<Card> pageTimeInfo = cardService.timeList(paramMap,page,size);
        modelMap.put("pageTimeInfo",pageTimeInfo);*/

        return "manager/building/buildDetail";
    }





    //---------------------------- property -------------------------------

    @Resource
    private BuildingService buildingService;

    @Resource
    private ResidenceService residenceService;

  /*  @Resource
    private UserService userService;
*/
    @Resource
    private UnitService unitService;

    @Resource
    private RoomService roomService;

 /*   @Resource
    private UserRoomService userRoomService;

    @Resource
    private EquipmentService equipmentService;

    @Resource
    private CardService cardService;

    @Resource
    private EquipmentCardService equipmentCardService;

    @Resource
    private PoliceResidenceService policeResidenceService;*/
    @Resource
    private EstateService estateService;

}
